package com.sk.server;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sk.mapper.SProjectMapper;
import com.sk.mapper.SUserMapper;
import com.sk.pojo.RespBean;
import com.sk.pojo.SProject;
import com.sk.utils.FdfsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class ProjectServer {

    @Autowired
    SProjectMapper sProjectMapper;

    @Autowired
    SUserMapper sUserMapper;

    public RespBean add(String name, String username, String content,
                        MultipartFile file, String mainPro, Integer score, String ip) {
        try {
            FdfsUtils fdfsUtils = new FdfsUtils();
            SProject sProject = new SProject();
            if (file != null) {
                String path = fdfsUtils.upload(file);
                sProject.setProUrl(ip + path);
            }
            sProject.setUid(sUserMapper.getIdByUsername(username));
            sProject.setName(name);
            sProject.setContent(content);
            sProject.setMainPro(mainPro);
            sProject.setScore(score);
            int insert = sProjectMapper.insert(sProject);
            if (insert > 0) {
                return RespBean.success("添加成功");
            } else {
                return RespBean.error("添加失败");
            }
        } catch (Exception e) {
            System.out.println(e);
            return RespBean.error("添加失败");
        }
    }

    public RespBean delete(Integer id) {

        int i = sProjectMapper.deleteById(id);
        if (i > 0) {
            return RespBean.success("删除成功");
        } else {
            return RespBean.error("删除失败");
        }
    }

    public List<SProject> like(String name) {
        QueryWrapper<SProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return sProjectMapper.selectList(queryWrapper);
    }

    public RespBean update(Integer id,String name, String username, String content,
                            MultipartFile file, String mainPro, Integer score,String ip){
        SProject sProject = new SProject();
        FdfsUtils fdfsUtils = new FdfsUtils();
        if (file != null) {
            String path = fdfsUtils.upload(file);
            sProject.setProUrl(ip + path);
        }

        sProject.setId(id);
        sProject.setUid(sUserMapper.getIdByUsername(username));
        sProject.setName(name);
        sProject.setContent(content);
        sProject.setMainPro(mainPro);
        sProject.setScore(score);

        int i = sProjectMapper.updateById(sProject);
        if (i > 0) {
            return RespBean.success("修改成功");
        } else {
            return RespBean.error("修改失败");
        }
    }


}
